from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By
from selenium.common.exceptions import NoSuchElementException
import allure

def findElementBy(selenium_web_driver,request, ByType,attribute, attribute_value):
    try:
        browser=request.config.getoption("--browser")
        wait = WebDriverWait(selenium_web_driver, 10)
        
        if  browser == 'chrome':
            if ByType == 'XPATH':
                element = wait.until(EC.visibility_of_all_elements_located((By.XPATH, attribute_value)))
            elif ByType == 'ID':
                element = wait.until(EC.visibility_of_all_elements_located((By.ID, attribute_value)))
            elif ByType == 'NAME':
                element = wait.until(EC.visibility_of_all_elements_located((By.NAME, attribute_value))) 
            elif ByType == 'CLASS_NAME':
                element = wait.until(EC.visibility_of_all_elements_located((By.NAME, attribute_value))) 
        elif browser == 'firefox':
            if ByType == 'XPATH':
                element = wait.until(EC.visibility_of_all_elements_located((By.XPATH, attribute_value)))
            elif ByType == 'ID':
                element = wait.until(EC.visibility_of_all_elements_located((By.ID, attribute_value)))
            elif ByType == 'NAME':
                element = wait.until(EC.visibility_of_all_elements_located((By.NAME, attribute_value)))  
            elif ByType == 'CLASS_NAME':
                element = wait.until(EC.visibility_of_all_elements_located((By.NAME, attribute_value)))                    
        elif browser == 'edge':
            if ByType == 'XPATH':
                element = wait.until(EC.visibility_of_all_elements_located((By.XPATH, attribute_value)))
            elif By == 'ID':
                element = wait.until(EC.visibility_of_all_elements_located((By.ID, attribute_value)))
            elif ByType == 'NAME':
                element = wait.until(EC.visibility_of_all_elements_located((By.NAME, attribute_value)))
            elif ByType == 'CLASS_NAME':
                element = wait.until(EC.visibility_of_all_elements_located((By.NAME, attribute_value)))                                                      
        else:
            raise ValueError("Unsupported browser: {}".format(browser))
        
        return element
    
    except NoSuchElementException as nsee:
        print(f"元素未找到错误: {nsee}")
        allure.attach(selenium_web_driver.get_screenshot_as_png(), name="元素未找到错误", attachment_type=allure.attachment_type.PNG)
        raise
    except Exception as e:
        print(f"未知错误: {e}")
        allure.attach(selenium_web_driver.get_screenshot_as_png(), name="未知错误", attachment_type=allure.attachment_type.PNG)
        raise